package com.sj.data;

import lombok.Data;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoqi
 * Date: 2022-07-25
 * Time: 上午 11:26
 * Description: 链表类
 *
 * @author xiaoqi
 * @since 2022-07-25
 */
@Data
public class NodeList<T, D> {

    /**
     * 头结点
     */
    private Node<T, D> head;

    /**
     * 添加
     *
     * @param node 需要添加的节点
     * @return 是否添加成功
     */
    public boolean add(Node<T, D> node) {
        // 如果添加的是第一个
        if (head == null) {
            head = node;
            return true;
        }
        // 不是第一个
        Node<T, D> temp = head;
        while (temp != null) {
            if (temp.getKey().equals(node.getKey())) {
                temp.setValue(node.getValue());
                return false;
            }
            if (temp.getNext() == null) {
                temp.setNext(node);
                return true;
            }
            temp = temp.getNext();
        }
        return false;
    }


    /**
     * 删除节点
     *
     * @param key 需要删除的节点的key
     * @return 当前链表
     * @throws RuntimeException 当链表为空时抛出异常
     */
    public NodeList<T, D> remove(T key) throws RuntimeException {
        if (head == null) {
            throw new RuntimeException("current list is empty!");
        }
        // 如果头结点就是需要删除的节点
        if (head.getKey().equals(key)) {
            head = head.getNext();
            return this;
        }
        Node<T, D> temp = head;
        while (temp != null) {
            if (temp.getNext() != null) {
                if (temp.getNext().getKey().equals(key)) {
                    temp.setNext(temp.getNext().getNext());
                }
            }
            temp = temp.getNext();
        }

        return this;
    }

    /**
     * 根据键获取值
     * @param key 键
     * @return 返回值
     */
    public D get(T key) {
        if (head == null) {
            return null;
        }
        Node<T, D> temp = head;
        while (temp != null) {
            if (temp.getKey().equals(key)) {
                return temp.getValue();
            }
            temp = temp.getNext();
        }
        return null;
    }

    public void print() {
        if (head == null) {
            System.out.println("empty!");
        }
        Node<T, D> temp = head;
        while (temp != null) {
            System.out.println(temp.getKey() + ": " + temp.getValue());
            temp = temp.getNext();
        }
    }

}